package com.merck.service.readsinkiang;

import com.amazonaws.HttpMethod;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import com.merck.service.export.SqlStr;
import com.merck.service.impl.ImportData;
import com.merck.service.impl.ImportDataServiceImpl;
import com.merck.service.read.ReadExcelImpl;
import com.merck.utils.DateUtils;
import com.merck.utils.ExcelReaderUtil;
import com.merck.utils.JDBCUtils;
import com.merck.utils.SendMail;
import org.apache.log4j.Logger;

import java.io.*;
import java.nio.channels.FileChannel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;
import java.util.Properties;

/**
 * @program: export_flow
 * @description: 导入参数表
 * @author: Lucas
 * @create: 2021-04-16 11:02
 **/
public class ReadSinking {
    private Logger log = Logger.getLogger(ReadExcelImpl.class);

    public void run() {
        System.out.println("开始导入数据-----------");
        AmazonS3 s3Client = null;
        Properties pro = new Properties();
        InputStream resourceAsStream = null;
        InputStream in = null;
        try {
            System.out.println("读取配置文件开始-----------");
            resourceAsStream = ReadExcelImpl.class.getResourceAsStream("/db.properties");
            pro.load(resourceAsStream);
            System.out.println("读取配置文件结束-----------");
        } catch (Exception e) {
            System.out.println("读取配置文件异常-----------");
            log.error(e.getMessage());
        } finally {
            if (resourceAsStream != null) {
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage());

                }
            }
        }


        //S3获取文件夹下所有的文件
        System.out.println("读取S3下的文件-----------");
        ImportData importData = new ImportDataServiceImpl();
        String bucketName = (String) pro.get("bucket.sinkiang");
        String path = (String) pro.get("remote.sinkiang");
        //备份路径
        String dateStr ="sinkiang"+ DateUtils.format(new Date(), "yyyyMMddHHmmss");
        String backBucketName = (String) pro.get("back.bucket.sinkiang");
        String backPath = (String) pro.get("back.remote.sinkiang") + dateStr + "/";
        s3Client = openS3ClientByEC2();
//        ListObjectsV2Result result = s3Client.listObjectsV2(bucketName, path);


        System.out.println("读取S3下的文件结束-----------");

        Connection connection = null;
        System.out.println("准备循环文件流-----------");
        System.out.println();
        System.out.println("开启JDBC----------");
        FileOutputStream downloadFile = null;
        try {
            connection = JDBCUtils.getConnection();
            //清空表数据；
            String delSql = "truncate lego_kpi_calculation.stg_kpi_south_sinkiang";
            PreparedStatement state = connection.prepareStatement(delSql);
            state.execute();

            File file;
                //备份
                s3Client.copyObject(bucketName, path, backBucketName, backPath + "south_sinkiang_list_added.xlsx");
                System.out.println("源桶：----"+bucketName);
                System.out.println("源健：-----"+path);
                System.out.println("目标桶：-----"+backBucketName);
                System.out.println("目标健：-----"+backPath);
                //获取要导入的文件
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
            S3Object s3Object = s3Client.getObject(getObjectRequest);
            in = s3Object.getObjectContent();
                //            写入文件
                int index;
                byte[] bytes = new byte[1024];
                downloadFile = new FileOutputStream("temp.xlsx");
                while ((index = in.read(bytes)) != -1) {
                    downloadFile.write(bytes, 0, index);
                    downloadFile.flush();
                }
                in.close();
                downloadFile.flush();
                FileChannel channel = downloadFile.getChannel();
                channel.force(true);
                FileDescriptor fd = downloadFile.getFD();
                fd.sync();
                downloadFile.close();
                file = new File("temp.xlsx");
                System.out.println("执行导入操作-----------");
                //备份excel
                ExcelReaderUtil.readExcel(importData, file, "lego_kpi_calculation.stg_kpi_south_sinkiang", connection);
                file.delete();
                log.info("导入当前excel表格成功");
//            }
            System.out.println("关闭JDBC----------");
            connection.close();
            System.out.println("导入excel表格成功-----------");
            String currentDateAsString = DateUtils.getCurrentDateAsString();
            SendMail.sendMail(null, null, "导入数据任务在 " + currentDateAsString + " 运行结果通知", SqlStr.SUCESS_SEND_CONTENT, null);
            log.info("导入excel表格成功");
        } catch (Exception e) {
            String currentDateAsString = DateUtils.getCurrentDateAsString();
            SendMail.sendMail(null, null, "导入数据任务在 " + currentDateAsString + " 运行结果通知", SqlStr.FAILURE_SEND_CONTENT, null);
            log.error(e.getMessage());
            throw new RuntimeException("导入数据失败:" + e.getMessage());
        }finally {
            try {
                if (downloadFile != null) {

                    downloadFile.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());

            }
        }
        //S3获取文件夹下所有的文件-结束

//本地测试
//        String importPath = (String) pro.get("import.path") + "meta_kpi_parameter.xlsx";
//        File file = new File(importPath);
//        File[] files = {};
//        if (file.isDirectory()) {
//            files = file.listFiles();
//            if (files.length < 1) {
//                log.error("文件夹中没有要导入的表格");
//                return;
//            }
//        }
//        本地循环导入excel中的数据
//        InputStream inputStream;
//        List<String> list = new ArrayList<>();
//        try {
//            connection = JDBCUtils.getConnection();
////            for (int i = 0; i < files.length; i++) {
//                try {
////                    MDC.put("start_time",new Date());
////                    File f = files[i];
//                    InputStream is = new FileInputStream(file);
//                    String substring = file.getName().substring(file.getName().lastIndexOf("/") + 1);
//    //            写入文件
//                    int index;
//                    byte[] bytes = new byte[1024];
//                    FileOutputStream downloadFile = new FileOutputStream(substring);
//                    while ((index = is.read(bytes)) != -1) {
//                        downloadFile.write(bytes, 0, index);
//                        downloadFile.flush();
//                    }
//                    is.close();
//                    downloadFile.flush();
//                    FileChannel channel = downloadFile.getChannel();
//                    channel.force(true);
//                    FileDescriptor fd = downloadFile.getFD();
//                    fd.sync();
//                    downloadFile.close();
////                    list.add(f.getName());
//
//                    File file1 = new File(substring);
//
//                    ExcelReaderUtil.readExcel(importData, importPath, "lego_kpi_calculation.stg_meta_kpi_parameter", connection);
//                    file1.delete();
////                    MDC.put("end_time",new Date());
//                    log.info("执行一次结束");
//                } catch (Exception e) {
//                    log.error(e.getMessage());
//                }
//
////            }
//            JDBCUtils.close();
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
////        创建备份文件夹
//        String backUpPath = pro.getProperty("backup.path");
//        String dateStr = DateUtils.format(new Date(), "yyyyMMddHHmmssSSS");
//        backUpPath = backUpPath + dateStr;
//        RecursionDir.copyDir(importPath,backUpPath);

    }


    public static AmazonS3 openS3ClientByEC2() {
        AmazonS3 s3Client = null;
        try {
            s3Client = AmazonS3ClientBuilder.defaultClient();
        } catch (Exception e) {
            throw new RuntimeException("获取S3客户端失败" + e.getMessage());
        }
        return s3Client;
    }

    private void GenerateExcelIntoS3(String remoteFileName, String bucketName, File file) {
//        File file = new File("temp.xlsx");
//        log.info("开始生成excel表格");
//        String bucketName = (String) pro.get("export.bucket.name");
//        importData.exportDataExcleApp(map, file, "excle", mapTitle, null);

        //S3环境运行代码开始
//        //把生成的Excel上传到S3，上传的路径为上面两个参数定义 ，为 s3://qa-lego-deployment/templates/ + fileName
//        //可以在HUE中查看
        AmazonS3 s3Client = null;
        try {
            s3Client = openS3ClientByEC2();

            PutObjectRequest poRequest = new PutObjectRequest(bucketName, remoteFileName, file).withCannedAcl(CannedAccessControlList.Private);
            s3Client.putObject(poRequest);
            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, remoteFileName, HttpMethod.POST);
            s3Client.generatePresignedUrl(urlRequest);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("将文件写入S3出错" + e.getMessage());
        } finally {
            if (s3Client != null) {
                s3Client.shutdown();
            }
        }
    }

}
